<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属阶段" prop="stage">
        <el-select v-model="queryParams.stage" placeholder="请选择所属阶段" clearable>
          <el-option
            v-for="dict in dict.type.sys_stage"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属星期" prop="week">
        <el-input
          v-model="queryParams.week"
          placeholder="请输入所属星期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测试类型" prop="testType">
        <el-select v-model="queryParams.testType" placeholder="请选择测试类型" clearable>
          <el-option
            v-for="dict in dict.type.ya_exam_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="测试内容" prop="testContent">
        <el-input
          v-model="queryParams.testContent"
          placeholder="请输入测试内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['teaching:weekly_reports:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['teaching:weekly_reports:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleScoreInput"
          v-hasPermi="['teaching:weekly_reports:score']"
        >成绩录入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="weekly_reportsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="周报ID" align="center" prop="id" />
      <el-table-column label="所属阶段" align="center" prop="stage">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_stage" :value="scope.row.stage"/>
        </template>
      </el-table-column>
      <el-table-column label="所属星期" align="center" prop="week" />
      <el-table-column label="所属班级" align="center" prop="className" />
      <el-table-column label="测试类型" align="center" prop="testType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ya_exam_type" :value="scope.row.testType"/>
        </template>
      </el-table-column>
      <el-table-column label="测试内容" align="center" prop="testContent" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['teaching:weekly_reports:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['teaching:weekly_reports:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 成绩录入对话框 -->
    <el-dialog title="学生成绩录入" :visible.sync="scoreDialogVisible" width="1100px" append-to-body>
      <el-form :model="scoreForm" label-width="100px">
        <el-form-item label="所属阶段" prop="stage">
          <el-select v-model="scoreForm.stage" placeholder="请选择所属阶段">
            <el-option
              v-for="dict in dict.type.sys_stage"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属星期" prop="week">
          <el-input v-model="scoreForm.week" placeholder="请输入所属星期" />
        </el-form-item>
        <el-form-item label="所属班级" prop="class">
          <!-- 修改 @change 事件，传递选中班级的 ID 给 getStudentNameList 方法 -->
          <el-select v-model="scoreForm.className" placeholder="请选择所属班级" @change="handleClassChange">
            <el-option
              v-for="item in classesList"
              :key="item.id"
              :label="item.className"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测试类型" prop="testType">
          <el-select v-model="scoreForm.testType" placeholder="请选择测试类型">
            <el-option
              v-for="dict in dict.type.ya_exam_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="测试内容" prop="testContent">
          <el-input v-model="scoreForm.testContent" placeholder="请输入测试内容" />
        </el-form-item>
        <!-- 添加分隔线 -->
        <el-divider></el-divider>
        <div v-for="(student, index) in studentNameList" :key="student.id">
          <el-row :gutter="15">
            <el-col :span="2">
              <el-form-item :label="student.name">
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="问题">
                <!-- 修改为 el-textarea 组件 -->
                <el-input type="textarea" v-model="scoreForm.studentScores[index].issues" placeholder="请输入存在问题" />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="建议">
                <!-- 修改为 el-textarea 组件 -->
                <el-input type="textarea" v-model="scoreForm.studentScores[index].instructorAdvice" placeholder="请输入讲师建议" />
              </el-form-item>
            </el-col>
          <template v-if="scoreForm.testType === '1'">
            <el-col :span="4">
              <el-form-item label="笔试">
                <el-input type="number" v-model="scoreForm.studentScores[index].writtenScore" />
              </el-form-item>
            </el-col>
          </template>
          <template v-if="scoreForm.testType === '2'">
            <el-col :span="4">
              <el-form-item label="机试">
                <el-input type="number" v-model="scoreForm.studentScores[index].practicalScore" />
              </el-form-item>
            </el-col>
          </template>
          <template v-if="scoreForm.testType === '3'">
            <el-col :span="4">
              <el-form-item label="笔试">
                <el-input type="number" v-model="scoreForm.studentScores[index].writtenScore" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="机试">
                <el-input type="number" v-model="scoreForm.studentScores[index].practicalScore" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="面试">
                <el-input v-model="scoreForm.studentScores[index].interviewScore" />
              </el-form-item>
            </el-col>
          </template>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStudentScores">提交</el-button>
        <!-- 修改这一行，绑定新的取消方法 -->
        <el-button @click="cancelScoreInput">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listWeekly_reports,
  getWeekly_reports,
  delWeekly_reports,
  addWeekly_reports, addStudent_scores, listStudent_name, updateWeekly_reports, deleteStudent_scores, getStudent_scores
} from "@/api/teaching/weekly_reports";
import { listClass } from "@/api/teaching/class";

export default {
  name: "Weekly_reports",
  dicts: ['sys_stage', 'ya_exam_type'],
  data() {
    return {
      // 学生成绩列表
      studentNameList: [],
      // 班级列表
      classesList: null,
      // 成绩录入表单
      scoreForm: {
        id: null, // 添加这一行
        stage: null,
        week: null,
        className: null,
        testType: null,
        testContent: null,
        studentScores: [] // 新增，用于存储每个学生的成绩信息
      },
      // 成绩录入对话框是否显示
      scoreDialogVisible: false,
      // 当前选择的班级
      selectedClass: null,
      // 学生列表
      studentList: [],
      // 学生成绩表单
      studentScores: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 周报表格数据
      weekly_reportsList: [],
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        stage: null,
        week: null,
        className: null,
        testType: null,
        testContent: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
    this.getClasses();
  },
  methods: {
    // 获取班级列表
    getClasses() {
      listClass().then(response => {
        this.classesList = response.rows;
      });
    },
    // 处理班级选择变化
    handleClassChange(item) {
      this.getStudentNameList(item.id); // 传递班级ID
      this.scoreForm.className = item.className; // 更新班级名称
    },
    // 获取学生姓名列表
    // 修改 getStudentNameList 方法，接收班级 ID 作为参数
    getStudentNameList(classesId) {
      // 假设 listStudent_name 是获取学生姓名列表的 API 方法
      // 这里将班级 ID 作为参数传递给 API 方法
      listStudent_name({classesId}).then(response => {
        this.studentNameList = response;
        console.log('学生姓名列表:', this.studentNameList); // 添加日志确认数据
        // 初始化 scoreForm.studentScores
        this.scoreForm.studentScores = this.studentNameList.map(() => ({
          issues: null,
          instructorAdvice: null,
          writtenScore: null,
          practicalScore: null,
          interviewScore: null
        }));
      });
    },
    // 打开成绩录入对话框
    handleScoreInput() {
      this.scoreDialogVisible = true;

    },
    // 提交学生成绩
    submitStudentScores() {
      // 提取上半部分表单数据
      const { stage, week, className, testType, testContent } = this.scoreForm;
      const weeklyReportData = {
        stage,
        week,
        className,
        testType,
        testContent
      };

      // 判断是新增还是更新
      const isUpdate = !!this.scoreForm.id; // 如果 scoreForm.id 存在，则是更新操作

      const savePromise = isUpdate
        ? updateWeekly_reports({ ...weeklyReportData, id: this.scoreForm.id }) // 更新周报
        : addWeekly_reports(weeklyReportData); // 新增周报

      savePromise.then(response => {
        const reportId = isUpdate ? this.scoreForm.id : response.data; // 如果是更新，使用已有ID；新增则获取新ID
        const studentScores = this.scoreForm.studentScores;

        // 封装学生成绩数据
        const studentScoreData = studentScores.map((score, index) => ({
          reportId,
          studentId: this.studentNameList[index].id,
          studentName: this.studentNameList[index].name,
          ...score
        }));

        // 先删除原有成绩（如果是更新操作）
        const updateProcess = isUpdate
          ? deleteStudent_scores(reportId).then(() => addStudent_scores(studentScoreData))
          : addStudent_scores(studentScoreData);

        updateProcess.then(() => {
          this.$modal.msgSuccess(`成绩${isUpdate ? '更新' : '录入'}成功`);
          this.scoreDialogVisible = false;
          this.getList();
        }).catch(error => {
          this.$modal.msgError(`成绩${isUpdate ? '更新' : '录入'}失败`);
        });
      }).catch(error => {
        this.$modal.msgError(`周报${isUpdate ? '更新' : '新增'}失败`);
      });
    },
    /** 查询周报列表 */
    getList() {
      this.loading = true;
      listWeekly_reports(this.queryParams).then(response => {
        this.weekly_reportsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        stage: null,
        week: null,
        className: null,
        testType: null,
        testContent: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    // 修改学生成绩录入
    handleUpdate(row) {
      // 重置表单
      this.resetScoreForm();

      // 将测试类型从 value 转换为 label
      // const testTypeLabel = this.dict.type.ya_exam_type.find(
      //   item => item.value === row.testType.toString()
      // )?.label;

      // 填充上半部分数据
      this.scoreForm = {
        id: row.id,
        stage: row.stage,
        week: row.week,
        className: row.className,
        //testType: testTypeLabel, // 使用转换后的 label
        testType: row.testType.toString(),
        testContent: row.testContent,
        studentScores: []
      };

      // 根据周报ID获取学生成绩数据
      getStudent_scores(row.id).then(response => {
        const reportData = response;

        // 填充学生成绩数据
        this.studentNameList = reportData.map(student => ({
          id: student.studentId,
          name: student.studentName
        }));

        this.scoreForm.studentScores = reportData.map(student => ({
          issues: student.issues,
          instructorAdvice: student.instructorAdvice,
          writtenScore: student.writtenScore,
          practicalScore: student.practicalScore,
          interviewScore: student.interviewScore
        }));

        // 打开对话框
        this.scoreDialogVisible = true;
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除周报编号为"' + ids + '"的数据项？').then(function() {
        return delWeekly_reports(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 新增取消成绩录入对话框的方法
    cancelScoreInput() {
      this.scoreDialogVisible = false; // 关闭对话框
      this.resetScoreForm(); // 重置成绩录入表单
    },
    // 重置成绩录入表单的方法
    resetScoreForm() {
      this.scoreForm = {
        id: null, // 添加这一行
        stage: null,
        week: null,
        className: null,
        testType: null,
        testContent: null,
        studentScores: []
      };
      this.studentNameList = []; // 清空学生姓名列表
    },
  }
};
</script>
